<?
require_once("includes/db.php"); 
require_once("includes/utils.php"); 

//
//  Outputs a string representation of the database settings.
//
//  The string is in the format:
//      
//      12112345123456789012345611
//      OK$hh:mmMessageOfTheeDay*&ABDCEFGHIJKLM... etc.
//
//      OKMessageOfTheDay %*&ABCDEF...
//
//  where:
//      '$' is the index of the weekday as an int e.g. "0" = "Sunday", "6" = "Saturday"
//      'hh:mm' is the current server time in 24 hour clock 
//      'MessageOfTheeDay' is an arbitrary 16-character string
//      '%' is the max temp as a one-char binary ASCII representation (with 100 added to it, e.g. 'd'=100="0C", 'x'=120="20C", 'Z'=90="-10C"
//      '*' is the appliances as an int (0=none, 1=hot water only, 2=hot water and central heating)
//      '&' is the advance status as an int (0=normal, 1=plus one hour, 2=advance)
//      '#' is the GPIO 1,2, and 3 status as a binary encoded int (0 = all off, 1 = GPIO1 on, 2 = GPIO2 on, 3 = GPIO 1&2 on, 7 = all 3 on).
//      'A', 'B', etc are binary representations of windows - grouped by day, with 3 windows per day and 2 events per day, 42 chars in total.
//      The binary representations are e.g. 101 for "10:00", 1 for "00:00", 236 for "23:50" (note we add 1 so that we don't send null chars).
//
//  There will be 26 bytes for everything before the windows, and 7*3*2 bytes (=42) for the windows, so that's 68 in total.
//  If there is an error then it will write out "ERR " followed by a message.
//

$db = new DB;

$resultset = $db->query ("  SELECT 
                                message_of_the_day,
                                appliances,
                                advance_status,
   		                        last_queried,
        		                last_updated_on_server,
                 	            last_updated_on_device,
                 	            max_temp,
                 	            gpio_1,
                 	            gpio_2,
                 	            gpio_3
                            FROM
                                heating");

if (! $resultset  ||  1 != mysql_num_rows ($resultset))
{
    ?>ERR heating <?=$db->getLastError()?><?
    return;
}




// Success!
$row = mysql_fetch_array($resultset);

$days = array();

$messageOfTheDay = $row["message_of_the_day"];
$appliances = $row["appliances"];
$advanceStatus = $row["advance_status"];
$lastQueried = $row["last_queried"];
$lastUpdatedOnServer = $row["last_updated_on_server"];
$lastUpdatedOnDevice = $row["last_updated_on_device"];
$maxTemp = $row["max_temp"];
$gpio1 = $row["gpio_1"];
$gpio2 = $row["gpio_2"];
$gpio3 = $row["gpio_3"];


$resultset = $db->query ("  SELECT
                                day,
                                window1_start,
                                window1_end,
                                window2_start,
                                window2_end,
                                window3_start,
                                window3_end
                            FROM
                                windows
                            ORDER BY
                                day ASC");


if (! $resultset  ||  7 != mysql_num_rows ($resultset))
{
    ?>ERR windows <?=$db->getLastError()?><?
    return;
}

// Success!
$days = array();

while ($row = mysql_fetch_array($resultset))
{
    $day = $row["day"];
        
    $days[$day] = array("window1_start" => $row["window1_start"],
                        "window1_end"   => $row["window1_end"],
                        "window2_start" => $row["window2_start"],
                        "window2_end"   => $row["window2_end"],
                        "window3_start" => $row["window3_start"],
                        "window3_end"   => $row["window3_end"]);
}                        
                           
//
//  END OF INITIAL DB QUERIES
// 



$data = $_GET['DATA'];
$logFile = fopen("log.txt", 'a') or die ("Can't open log file");
fputs($logFile, date("Y-m-d H:i:s") . " Request with ?" . $data . "\n");



date_default_timezone_set("Europe/London");
$sDayIndex = date("w");
$sTime = date("H:i");



// Validation and saving
if (strlen($data) > 0)
{
    //
    // Should be in the format:
    //
    //  <isStateChangedLocally>_<lastSyncSendTime>_<lastSyncSuccessTime>_<appliances>_<advanceStatus>_<ambientTemp>_<maxTemp>_<day1window1startTime>_<day1window1endTime>_<day1window2startTime>_<day1window2endTime>_etc.
    //  There should be 7 'general' parts, plus 6*7 window times = 7+42 = 49 parts in total    
    //
    $parts = explode("_", $data);
    if (47 == sizeof($parts))
    {
        if ("Y" == $parts[0])  // state is changed locally
        {
            $appliances = $parts[3];
            $advanceStatus = $parts[4];
            $ambientTemp = $parts[5];
            $maxTemp = $parts[6];
            
            if (! preg_match("/^[012]$/", $appliances))
            {
                ?>ERR param appliances: <?=$appliances?><?
                return;
            }
            if (! preg_match("/^[012]$/", $advanceStatus))
            {
                ?>ERR param advanceStatus: <?=$advanceStatus?><?
                return;
            }
            
            
            // Save
            $resultset = $db->query ("UPDATE heating SET 
                              appliances         = " . makeSafeForDB($appliances) . ",
                              advance_status     = " . makeSafeForDB($advanceStatus) . ",
                              max_temp           = " . makeSafeForDB($maxTemp));
            
            for ($iDay = 0; $iDay < 7; $iDay++)
            {
                $iStartIndex = 7 + (6 * $iDay);
                
                $resultset = $db->query ("UPDATE windows SET
                                              window1_start = " . makeSafeForDB($parts[iStartIndex+0]) . ",
                                              window1_end   = " . makeSafeForDB($parts[iStartIndex+1]) . ",
                                              window2_start = " . makeSafeForDB($parts[iStartIndex+2]) . ",
                                              window2_end   = " . makeSafeForDB($parts[iStartIndex+3]) . ",
                                              window3_start = " . makeSafeForDB($parts[iStartIndex+4]) . ",
                                              window3_end   = " . makeSafeForDB($parts[iStartIndex+5]) . "
                                          WHERE day = " . $iDay);                
            }
            
            // TODO - check for success
        }        
    }
}


$windowsString = "";

for ($day=0; $day < 7; $day++)
{
    for ($window=0; $window < 3; $window++)
    {
        // Add binary representation of our tiny int (add 1 to each value so C++ doesn't have problems with NULL/0s)   
        $windowsString = $windowsString . chr(1 + ($days[$day]["window" . ($window + 1) . "_start"]));
        $windowsString = $windowsString . chr(1 + ($days[$day]["window" . ($window + 1) . "_end"]));
    }
}

$messageOfTheDay = substr($messageOfTheDay, 0, 16);

while (strlen($messageOfTheDay) < 16)
{
    $messageOfTheDay = $messageOfTheDay . " ";
}   

$maxTempBinary = chr(100 + floor($maxTemp));
$iGPIO = 0;
$iGPIO += ($gpio1 ? 1 : 0);
$iGPIO += ($gpio2 ? 2 : 0);
$iGPIO += ($gpio3 ? 4 : 0);

//$windowsString = "";
// Dhh:mmMessageOfTheeDayABCDEEEFFFGGGHHHIIIJJJKKKLLLMMM etc.

fclose($logFile);
?>OK<?=$sDayIndex?><?=$sTime?><?= $messageOfTheDay ?><?=$maxTempBinary?><?=$appliances?><?=$advanceStatus?><?=$iGPIO?><?=$windowsString?>DONE